package light3d;


public class Triangle extends PointWithAngle
{
	public Point3D[] p;
	public Point3D normal = new Point3D(0,0,0);
	public Point3D baseNormal;
  public Point3D lightNormal;
	
	public int texture = -1;
	private int cullDirection = 1;
	
	public Triangle(int surfaceColor, Point3D p1, Point3D p2, Point3D p3)
	{
		super(0,0,0);
		
		baseNormal = new Point3D();
		
		p = new Point3D[3];
		p[0] = p1.clone();
		p[1] = p2.clone();
		p[2] = p3.clone();
		
		color = surfaceColor;
		computeNormal();
	}
	public Triangle(int surfaceColor, 
			 double x1, double y1, double z1,
			 double x2, double y2, double z2,
			 double x3, double y3, double z3)
	{
		super(0,0,0);
		
		baseNormal = new Point3D();
		
		p = new Point3D[3];
		p[0] = new Point3D(x1,y1,z1);
		p[1] = new Point3D(x2,y2,z2);
		p[2]= new Point3D(x3,y3,z3);
		
		color = surfaceColor;
		computeNormal();
	}
	Triangle(int surfaceColor)
	{
		super(0,0,0);
		baseNormal = new Point3D();
		
		p = new Point3D[3];
		p[0] = new Point3D(0,0,0);
		p[1] = new Point3D(0,0,0);
		p[2] = new Point3D(0,0,0);
		
		color = surfaceColor;
		computeNormal();
	}
	public void resetPointChanges()
	{
		
		for (int i = 0; i < 3; i++)
		{
			p[i].resetChanges();
		}
		normal = baseNormal.clone();
	}
	public void rotate(double x, double y, double z)
	{
		rX += x;
		rY += y;
		rZ += z;
		if (normal != null)
		{
			normal.rotate(x, y, z);
		}
	}
	public void computeNormal()
	{
		
		Point3D u = p[1].subtract(p[0]);
		Point3D v = p[2].subtract(p[0]);
		baseNormal.setX(u.getY()*v.getZ() - u.getZ()*v.getY());
		baseNormal.setY(u.getZ()*v.getX() - u.getX()*v.getZ());
		baseNormal.setZ((u.getX()*v.getY() - u.getY()*v.getX())*cullDirection);
		baseNormal.normalize();
		
		normal = baseNormal.clone();
    lightNormal = baseNormal.clone();
	}
	public void reverseCull()
	{
		cullDirection = -cullDirection;
	}
	public void setBaseNormal(Point3D point3D)
	{
		baseNormal = point3D.clone();
		normal = baseNormal.clone();
	}
	public void finalizeCoordinates()
	{
		origX = tempX;
		origY = tempY;
		origZ = tempZ;
		origRX = rX;
		origRY = rY;
		origRZ = rZ;
		if (normal != null)
		{
			setBaseNormal(normal);
		}
	}
	public void translateUV(double u, double v)
	{
		for (int i = 0; i < 3; i++)
		{
			p[i].translateUV(u,v);
		}
	}
  public void freezeLightNormal()
  {
    lightNormal = normal.clone();
  }
}
